package com.wang.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

import org.junit.Test;

public class ChannelTest {

	private CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();
//	private CharsetDecoder decoder2 = java.nio.charset.StandardCharsets.UTF_8.newDecoder();
	
	


	@Test
	public void test(){
		
		try(FileChannel inChannel = new FileInputStream("save.txt").getChannel();
				FileChannel outChannel = new FileOutputStream("attach.txt").getChannel()){
			//Channel对应的部分或全部数据映射成ByteBuffer
			MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY,0, new File("save.txt").length());
			Util.displayBufferInfo(buffer, "buffer init");
				
			// 将Buffer内容一次写入另一文件的Channel
			outChannel.write(buffer);
			buffer.flip();
			//解码CharBuffer之后输出
			System.out.println(decoder.decode(buffer));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
